package com.antoco.operation.bigscreen.service.autogeneration.impl;

import com.antoco.operation.bigscreen.repository.SensorImgRepository;
import com.antoco.operation.bigscreen.model.entity.SensorImg;
import com.antoco.operation.bigscreen.service.autogeneration.intf.SensorImgService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SensorImgServiceImpl extends AbstractModelServiceImpl implements SensorImgService {

    @Autowired
    private SensorImgRepository repository;

    @Override
    public SensorImg save(SensorImg entity) {
        return repository.save(entity);
    }

    @Override
    public List<SensorImg> save(List<SensorImg> entities) {
        List<Long> sensorIds = new ArrayList<Long>();
        // 去掉重复的sensor_id
        for (SensorImg entity : entities) {
            Long id = entity.getSensorId();
            if (!sensorIds.contains(id)) {
                sensorIds.add(id);
            }
        }
        // 先删除已有的图片
        repository.deleteAllBySensorIdIn(sensorIds);
        return (List<SensorImg>) repository.saveAll(entities);
    }

    @Override
    public void deleteById(String id) {
        repository.deleteById(Long.valueOf(id));
    }

    @Override
    public Optional<SensorImg> findById(String id) {
        return repository.findById(Long.valueOf(id));
    }

    @Override
    public List<SensorImg> findAllBySensorId(Long sensorId) {
        return (List<SensorImg>) repository.findAllBySensorId(sensorId);
    }

    @Override
    public List<SensorImg> findAll() {
        return (List<SensorImg>) repository.findAll();
    }

    @Override
    public Page<SensorImg> findAll(Pageable pageable) {
        Page<SensorImg> entityPage = repository.findAll(pageable);
        List<SensorImg> entities = entityPage.getContent();
        return new PageImpl<>(entities, pageable, entityPage.getTotalElements());
    }

    @Override
    public SensorImg update(SensorImg entity, String id) {
        Optional<SensorImg> optional = findById(id);
        if (optional.isPresent()) {
            return save(entity);
        }
        return null;
    }
}